const { Controller } = require('egg');

class BaseController extends Controller {
  get user() {
    return this.ctx.session.user;
  }

  success(data) {
    this.ctx.body = {
      code: 200,
      data,
    };
  }

  grid({ ng = {}, data = []}) {
    const {
      totalPages: total
    } = ng

    this.success({
      total,
      data
    })
  }

  page(params = {}) {
    const {
      temp,
      page: cp,
      size: pageSize,
      field = 'createDate',
      sort = 'desc',
      ...rest
    } = params
    return {
      page: {
        pageSize: pageSize ? Number(pageSize) : 20,
        cp: cp ? Number(cp) : 1,
        order: {
          field,
          sort
        }
      },
      ...rest
    }
  }

  exception(data) {
    if (data) {
      const {
        code,
        msg: message
      } = data
      this.error(code, message)
    }
  }

  error(code, message) {
    this.ctx.body = {
      code,
      message,
    };
    this.ctx.status = code
  }

  notFound(msg) {
    msg = msg || 'not found';
    this.ctx.throw(404, msg);
  }
}

module.exports = BaseController;